﻿#ifndef ACTIONCOMMANDER_H
#define ACTIONCOMMANDER_H

#include <head/g_pch.h>
#include <head/db_helper.h>
#include <support/ref_commands.h>

#define TBL_LAUNCHER "p_launcher"
#define TBL_CMD "p_command"
#define TBL_SITE "p_site"
#define TBL_PREFIX "td_prefix"

#define PRE_SEARCH "https://www.baidu.com/s?wd="

class ActionCommander
{
public:
    void execute(int code, QStringList params)
    {
        switch (code) {
        case CMD_ACT_OPEN:
            if(params.size() < 1)
                return;
            open(params);
            break;
        case CMD_ACT_SEARCH:
            if(params.size() < 1)
                return;
            search(params);
            break;
        case CMD_ACT_PREFIX:
            do_prefix(params);
            break;
        }
    }

private:
    QString findPrefix(const QString &kw)
    {
        return sp_findItem("detail",TBL_PREFIX,"alias",kw);
    }

    QString findUrl(const QString &kw)
    {
        return sp_findItem("detail",TBL_SITE,"alias",kw);
    }

    QString findCommand(const QString &kw)
    {
        QString detail=sp_getItem("detail",TBL_LAUNCHER,"label",kw).toString();
        if(!detail.isEmpty())
            return detail;

        return sp_findItem("detail",TBL_CMD,"alias",kw);
    }

    void do_prefix(const QStringList &params)
    {
        QString url;
        if(params.size() == 1)
            url=findUrl(params.first());
        else
        {
            QString prefix=findPrefix(params.first());
            auto items=params;
            items.removeFirst();
            url=prefix + items.join(" ");
        }
        QDesktopServices::openUrl(QUrl(url));
    }

    void search(const QStringList &params)
    {
        QString url;
        if(params.size() == 1)
            url=PRE_SEARCH + params.first();
        else
        {
            QString prefix=findPrefix(params.first());
            auto items=params;
            items.removeFirst();
            url=prefix + items.join(" ");
        }
        QDesktopServices::openUrl(QUrl(url));
    }

    void open(const QStringList &params)
    {
        QString detail=findUrl(params.first());
        if(!detail.isEmpty())
        {
            QDesktopServices::openUrl(QUrl(detail));
            return;
        }

        detail=findCommand(params.first());
        if(!detail.isEmpty())
        {
            QProcess::startDetached(detail,QStringList());
            return;
        }
    }
};

#endif // ACTIONCOMMANDER_H
